package com.ai.deepseekspring.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class blConfig implements WebMvcConfigurer {

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;

    private final String BAILIAN_DEEPSEEK_MODEL = "deepseek-v3";
    private final String BAILIAN_QWEN_MODEL = "qwen-plus";





    // 配置Deepseek模型的ChatModel
    @Bean("deepseekChatModel")
    public OpenAiChatModel deepseekChatModel() {
        return OpenAiChatModel.builder()
                .openAiApi(createOpenAiApi())
                .defaultOptions(OpenAiChatOptions.builder()
                        .model(BAILIAN_DEEPSEEK_MODEL)
                        .build())
                .build();
    }

    // 配置Qwen模型的ChatModel
    @Bean("qwenChatModel")
    public OpenAiChatModel qwenChatModel() {
        return OpenAiChatModel.builder()
                .openAiApi(createOpenAiApi())
                .defaultOptions(OpenAiChatOptions.builder()
                        .model(BAILIAN_QWEN_MODEL)
                        .build())
                .build();
    }



    @Bean("deepseekChatClient")
    public ChatClient deepseekChatClient() {
        return ChatClient.builder(deepseekChatModel()).build();
    }

    @Bean("qwenChatClient")
    public ChatClient qwenChatClient() {
        return ChatClient.builder(qwenChatModel()).build();
    }

    // 抽取OpenAiApi创建逻辑，避免重复代码
    private OpenAiApi createOpenAiApi() {
        return OpenAiApi.builder()
                .apiKey(apiKey)
                .baseUrl(baseUrl)
                .build();
    }

    // 配置CORS支持，解决跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}
